﻿namespace AzureCamp.RssAggregatorBusiness
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.IO;
    using System.Linq;
    using System.ServiceModel.Syndication;
    using System.Xml;

    public class RssHelper
    {

        public static SyndicationFeed CreateAgregator(List<string> rssUrls, int numberOfPost)
        {
            return CreateAgregator("Unknown", "No Description", rssUrls, numberOfPost);
        }

        public static SyndicationFeed CreateAgregator(string title, string description, List<string> rssUrls, int numberOfPost)
        {
            Collection<SyndicationFeed> feeds = new Collection<SyndicationFeed>();
            foreach (string url in rssUrls)
            {
                using (XmlReader feedReader = XmlReader.Create(url))
                {
                    SyndicationFeed syndication = SyndicationFeed.Load(feedReader);
                    feeds.Add(syndication);
                }
            }

            DateTime minDate = DateTime.Now.AddDays(-30);

            var mashedItems =
                from feed in feeds
                from item in feed.Items
                //where item.PublishDate > minDate
                orderby item.PublishDate descending
                select item;

            SyndicationFeed mashedFeed = new SyndicationFeed(mashedItems.Take(numberOfPost));
            //SyndicationFeed mashedFeed = new SyndicationFeed(mashedItems);
            mashedFeed.Title = TextSyndicationContent.CreatePlaintextContent(title);
            mashedFeed.Description = TextSyndicationContent.CreatePlaintextContent(description);
            return mashedFeed;
        }

        public static void SaveSyndicationFeedAsXml(SyndicationFeed feed, string outputfileName)
        {
            XmlTextWriter writer = new XmlTextWriter(outputfileName, System.Text.Encoding.UTF8);
            feed.SaveAsRss20(writer);
            writer.Flush();
            writer.Close();
        }

        public static void SaveSyndicationFeedAsXml(SyndicationFeed feed, Stream stream)
        {
            XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8);
            feed.SaveAsRss20(writer);
            writer.Flush();
            writer.Close();
        }

    }
}
